package com.pig4cloud.pigx.wms.webtools;

import java.security.MessageDigest;

import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;


@Slf4j
public class GuanYiWebToolsTestTools {

	private static String url = "http://v2.api.guanyierp.com/rest/erp_open";

	private static String appkey = "112194";

	private static String sessionkey = "567f4d242e794c75b6748e54326a9bff";

	private static String secret = "7d3330562019420da7f3098aa630556b";


	public static String getErpShop(){

		String method = "gy.erp.shop.get";
		JSONObject sendJsonObj = JSONUtil.createObj();
		sendJsonObj.set("appkey",appkey);
		sendJsonObj.set("sessionkey",sessionkey);
		sendJsonObj.set("method",method);

		String sign = sign(sendJsonObj.toString(),secret);

		sendJsonObj.set("sign",sign);

		String jsonData = sendJsonObj.toString();

		log.info("获取店铺原始json:" + jsonData);

		return sendPost(url,jsonData);

	}

	public static String getDeliverys(String startDateTime,String endDateTime){

		String method = "gy.erp.trade.deliverys.get";

		JSONObject sendJsonObj = JSONUtil.createObj();

		sendJsonObj.set("appkey",appkey);
		sendJsonObj.set("sessionkey",sessionkey);
		sendJsonObj.set("method",method);
		sendJsonObj.set("start_create",startDateTime);
		sendJsonObj.set("end_create",endDateTime);
		sendJsonObj.set("delivery","0");

		String sign = sign(sendJsonObj.toString(),secret);

		sendJsonObj.set("sign",sign);

		String jsonData = sendJsonObj.toString();

		log.info("调用查询发货单...原始json:" + jsonData);

		return sendPost(url,jsonData);

	}

	public static String updateDeliverys(String orderCode){

		String method = "gy.erp.trade.deliverys.update";

		JSONObject sendJsonObj = JSONUtil.createObj();

		JSONArray sendJsonArr = JSONUtil.createArray();
		JSONObject sendJsonSubObj = JSONUtil.createObj();
		sendJsonSubObj.set("area_id",4);
		sendJsonSubObj.set("operator","wms操作人");
		sendJsonSubObj.set("operator_date","2021-08-19 16:30:10");


		sendJsonObj.set("appkey",appkey);
		sendJsonObj.set("sessionkey",sessionkey);
		sendJsonObj.set("method",method);
		sendJsonObj.set("code",orderCode);
		sendJsonArr.add(sendJsonSubObj);
		sendJsonObj.set("deliverys_state_paramlist",sendJsonArr);

		String sign = sign(sendJsonObj.toString(),secret);

		sendJsonObj.set("sign",sign);

		String jsonData = sendJsonObj.toString();

		log.info("调用修改发货单...原始json:" + jsonData);

		return sendPost(url,jsonData);

	}

	public static String sendPost(String url, String data) {

		log.info("发送管易请求的url:   " + url);

		log.info("发送给管易的请求是:   " + data);

		try {

			CloseableHttpClient httpclient = null;

			CloseableHttpResponse httpresponse = null;

			try {

				httpclient = HttpClients.createDefault();

				HttpPost httppost = new HttpPost(url);

				StringEntity stringentity = new StringEntity(

						data,

						ContentType.create("text/json", "UTF-8"));

				httppost.setEntity(stringentity);

				httpresponse = httpclient.execute(httppost);

				String response = EntityUtils

						.toString(httpresponse.getEntity());

				log.info("请求管易系统后,响应是:   " + response);

				return response;

			} finally {

				if (httpclient != null) {

					httpclient.close();

				}

				if (httpresponse != null) {

					httpresponse.close();

				}

			}

		} catch (Exception e) {

			e.printStackTrace();

		}
		return null;
	}

	/**
	 * @Author: 高欣
	 * @Date: 2021/7/11 20:03
	 * 签名方法
	 */
	public static String sign(String str, String secret) {

		log.info("source:   " + str);

		log.info("secret:   " + secret);

		StringBuilder enValue = new StringBuilder();

		enValue.append(secret);

		enValue.append(str);

		enValue.append(secret);

		log.info("append   secret: " + enValue.toString());

		log.info("sign:   " + encryptByMD5(enValue.toString()));

		return encryptByMD5(enValue.toString());

	}

	/**
	 * @Author: 高欣
	 * @Date: 2021/7/11 20:03
	 * MD5加密方法
	 */
	private static String encryptByMD5(String data) {

		StringBuilder sign = new StringBuilder();

		try {

			MessageDigest md = MessageDigest.getInstance("MD5");

			byte[] bytes = md.digest(data.getBytes("UTF-8"));

			for (int i = 0; i < bytes.length; i++) {

				String hex = Integer.toHexString(bytes[i] & 0xFF);

				if (hex.length() == 1) {

					sign.append("0");

				}

				sign.append(hex.toUpperCase());

			}

		} catch (Exception e) {

			e.printStackTrace();

		}

		return sign.toString();

	}

	public static void main(String[] args) {

//		System.out.println(getErpShop());

		String resopnseJson = updateDeliverys("SDO370177822558");

		System.out.println(resopnseJson);

		JSONObject jsonObject = JSONUtil.parseObj(resopnseJson);

//		String resopnseJson = getDeliverys("2021-08-18 15:00:00","2021-08-18 16:00:00");

//		JSONObject jsonObject = JSONUtil.parseObj(resopnseJson);

//		boolean success = jsonObject.getBool("success");

//		int total = jsonObject.getInt("total");

//		System.out.println("yes");

//		System.out.println(sign("{\"appkey\":\"112194\",\"sessionkey\":\"567f4d242e794c75b6748e54326a9bff\","
//				+ "\"method\":\"gy.erp.trade.deliverys.get\",\"start_create\":\"2021-07-01 00:00:00\","
//				+ "\"end_create\":\"2021-07-11 00:00:00\",\"delivery\":\"0\"}", "7d3330562019420da7f3098aa630556b"));
	}
}
